package org.xawl.news.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JDBCUtil {
	// 创建唯一实例
	private static JDBCUtil ONLY;
	// 私有化成员变量，防止影响其他类共有的变量
	private static String DRIVER;
	private static String URL;
	private static String USERNAME;
	private static String PASSWORD;

	// 屏蔽外部的new
	private JDBCUtil() {
		try {
			ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
			DRIVER = bundle.getString("driverClassName");
			URL = bundle.getString("url");
			USERNAME = bundle.getString("username");
			PASSWORD = bundle.getString("password");
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 提供一个全局访问点
	public static JDBCUtil getInstance() {
		// ....其它代码
		if (ONLY == null) {
			// B线程等待
			synchronized (JDBCUtil.class) {
				if (ONLY == null) {
					ONLY = new JDBCUtil();
					// A线程创建
				}
			}
		}
		// ....其它代码
		return ONLY;
	}

	// 连接驱动的方法需要执行跟多次，作为一个普通方法就行
	public Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 归还资源
	public void close(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void rollback(Connection conn) {
		try {
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
